package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Document;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.Page;
import com.kaishengit.util.db.RowMapper;

public class DocumentDao {

	private DBHelp<Document> db = new DBHelp<Document>();
	
	public void save(Document dt){

		String sql = "insert into t_document(id,content,title,userid,projectid,createtime) values (?,?,?,?,?,?)";
		db.executeSQL(sql,dt.getId(),dt.getContent(),dt.getTitle(),dt.getUserid(),dt.getProjectid(),dt.getCreatetime());

		
	}
	public void update(Document dt){
		String sql = "update t_document set content=?, title=?,projectid=?,userid=? where id=?";
		db.executeSQL(sql, dt.getContent(),dt.getTitle(),dt.getProjectid(),dt.getUserid(),dt.getId());
	}
	public void del(String id){
		String sql = "delete from t_document where id=?";
		db.executeSQL(sql, id);
	}
	public List<Document> findAll(){

		String sql="select id,content,title,userid,projectid,username,createtime order by createtime desc from t_document";

		return db.executeQueryToList(sql, new DtRowMapper());
	}

	

	
	public Page<Document> findByPageAndProjectId(String projectId, int pageNum){
		String sql="select id,content,title,userid,projectid,createtime from t_document where projectid = ? limit ?,?";

		Page<Document> page = new Page<Document>(count(),pageNum);
		page.setList(db.executeQueryToList(sql, new DtRowMapper(),projectId,page.getStart(),page.getPageSize()));
		return page;
	}
	
	
	private int count() {
		String sql="select count(*) from t_document";
		return db.executeQuery(sql).intValue();
	}

	public Document findById(String id){
		String sql="select id,content,title,userid,projectid,createtime from t_document where id=? ";
		return db.executeQueryToObject(sql, new DtRowMapper(), id);	
	}
	public class DtRowMapper implements RowMapper<Document>{

		public Document mapRow(ResultSet rs) throws SQLException {
			Document dt = new Document();
			dt.setId(rs.getString("id"));
			dt.setContent(rs.getString("content"));
			dt.setCreatetime(rs.getString("createtime"));
			dt.setTitle(rs.getString("title"));
			dt.setProjectid(rs.getString("projectid"));
			dt.setUserid(rs.getString("userid"));
			
			return dt;
		}
		
	}
}
